#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <arpa/inet.h>
#include "dfs_messages.h"
#include "dfs_client.h"
#include "sglib.h"

#define OPENEDFILELIST_COMPARATOR(e1, e2) (strcmp(e1->filename,e2->filename))

SGLIB_DEFINE_LIST_PROTOTYPES(openedFileList, OPENEDFILELIST_COMPARATOR, next)
SGLIB_DEFINE_LIST_FUNCTIONS(openedFileList, OPENEDFILELIST_COMPARATOR, next)


/* handles opened_fd list */
void handle_opened_fd_list(const char *filename, int util){
    
    openedFileList *l_op_file_nentry, *l, *result, *res;
    struct sglib_openedFileList_iterator it;
    l_op_file_nentry = malloc(sizeof(openedFileList));
    sprintf(l_op_file_nentry->filename, "%s",filename);
    if( util == OPEN ){
		res = sglib_openedFileList_find_member(the_list,l_op_file_nentry);
        if(res == NULL)
        	sglib_openedFileList_add(&the_list,l_op_file_nentry);
        else
            printf("File is already opened.\n");
    }
    else if( util == CLOSE ){
        res = sglib_openedFileList_find_member(the_list,l_op_file_nentry);
        if(res != NULL)
            sglib_openedFileList_delete_if_member(&the_list, l_op_file_nentry, &result);
        else
            printf("File is not opened.\n");
        printf("===================\n");
    }
	printf("[OPENED FILES]\n");
	for(l=sglib_openedFileList_it_init(&it,the_list); l!=NULL; l=sglib_openedFileList_it_next(&it))
        printf("[%s]\n", l->filename);
	printf("==============\n");
}
/* checks if file is opened */
int check_if_opened(const char *filename){
	openedFileList l_op_file,*res;
	memset(l_op_file.filename,0,NAME_MAX);
	memcpy(l_op_file.filename,filename,strlen(filename));
	
	res = sglib_openedFileList_find_member(the_list,&l_op_file);
	
	if(res == NULL) return ERROR;
	
	return OK;
}